/*
 * (C) 2005 National Australia Bank
 *
 * [All rights reserved]. This product and related documentation are protected
 * by copyright restricting its use, copying, distribution, and decompilation.
 * No part of this product or related documentation may be reproduced in any
 * form by any means without prior written authorization of
 * National Australia Bank. Unless otherwise arranged, third parties may not
 * have access to this product or related documents.
 */
package au.com.evoCoach.service;

import java.util.Iterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import au.com.evoCoach.dao.PlayerForRoundDAO;
import au.com.evoCoach.dao.RoundDAO;
import au.com.evoCoach.dao.TeamPlayerDAO;
import au.com.evoCoach.domain.PlayerForRound;
import au.com.evoCoach.domain.Team;
import au.com.evoCoach.domain.TeamPlayer;
import au.com.evoCoach.enums.Position;
import au.com.evoCoach.form.TeamSubmissionForm;

@Service
public class PlayerForRoundService {
	private PlayerForRoundDAO playerForRoundDAO;
	private TeamPlayerDAO teamPlayerDAO;
	private RoundDAO roundDAO;

	@Autowired
	public PlayerForRoundService(PlayerForRoundDAO playerForRoundDAO, TeamPlayerDAO teamPlayerDAO, RoundDAO roundDAO) {
		this.playerForRoundDAO = playerForRoundDAO;
		this.teamPlayerDAO = teamPlayerDAO;
		this.roundDAO = roundDAO;
	}
	
	public void submitTeamForRound(TeamSubmissionForm teamSubmissionForm, Team team) {
	    playerForRoundDAO.deletePlayersForRound(team);
	    
	    for (Iterator<String> keyIter = teamSubmissionForm.getPlayerPositions().keySet().iterator(); keyIter.hasNext();) {
	        String fieldName = keyIter.next();
	        Position position = Position.DEF;
	        if (fieldName.startsWith("F")) {
	            position = Position.FWD;
	        }
	        else if (fieldName.startsWith("R")) {
	            position = Position.RUCK;
	        }
	        else if (fieldName.startsWith("M")) {
                position = Position.MID;
            }
	        
	        PlayerForRound playerForRound = new PlayerForRound();
	        playerForRound.setPlayerPosition(position);
	        if (teamSubmissionForm.getPlayerPositions().get(fieldName) != null && teamSubmissionForm.getPlayerPositions().get(fieldName) != -1) {
	        	TeamPlayer teamPlayer = (TeamPlayer) teamPlayerDAO.findById(teamSubmissionForm.getPlayerPositions().get(fieldName));
	            playerForRound.setTeamPlayer(teamPlayer);
		        playerForRound.setRound(roundDAO.getCurrentRound());
		        
		        playerForRoundDAO.save(playerForRound);
	        }
	    }
	}
	
}
